home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 3: Developer Tools / Linux Cubed Series 3 - Developer Tools.iso / utils / file / managers / mc-3.2 / mc-3 / mc-3.2.1 / nt / getopt.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-05-17  |  19.5 KB  |  619 lines

  1. /* This file taken from Midnight Commander 1.1. port to DOS. */
  2. /* this version is slightly modified for the midnight commander
  3.    port to 80286 machines */   
  4. /* Getopt for GNU.
  5.    Copyright (C) 1987, 1989, 1990 Free Software Foundation, Inc.
  6.  
  7.    This program is free software; you can redistribute it and/or modify
  8.    it under the terms of the GNU General Public License as published by
  9.    the Free Software Foundation; either version 1, or (at your option)
  10.    any later version.
  11.  
  12.    This program is distributed in the hope that it will be useful,
  13.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  14.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  15.    GNU General Public License for more details.
  16.  
  17.    You should have received a copy of the GNU General Public License
  18.    along with this program; if not, write to the Free Software
  19.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  20. #define MSDOS
  21. #define STDC_HEADERS
  22. /* MS-DOS port (c) 1990 by Thorsten Ohl, td12@ddagsi3.bitnet
  23.    This port is distributed under the terms of the GNU General
  24.    Public License as published by the Free Software Foundation.
  25.  
  26.    $Header: e:/gnu/lib/RCS/getopt.c 1.1.0.1 90/09/11 09:46:00 tho Exp $
  27.  */
  28. #ifdef __STDC__
  29. #define CONST const
  30. #else
  31. #define CONST
  32. #endif
  33.  
  34. /* This version of `getopt' appears to the caller like standard Unix `getopt'
  35.    but it behaves differently for the user, since it allows the user
  36.    to intersperse the options with the other arguments.
  37.  
  38.    As `getopt' works, it permutes the elements of `argv' so that,
  39.    when it is done, all the options precede everything else.  Thus
  40.    all application programs are extended to handle flexible argument order.
  41.  
  42.    Setting the environment variable _POSIX_OPTION_ORDER disables permutation.
  43.    Then the behavior is completely standard.
  44.  
  45.    GNU application programs can use a third alternative mode in which
  46.    they can distinguish the relative order of options and other arguments.  */
  47.  
  48. #include <stdio.h>
  49.  
  50. /* If compiled with GNU C, use the built-in alloca */
  51. #ifdef __GNUC__
  52. #define alloca __builtin_alloca
  53. #else /* not __GNUC__ */
  54. #ifdef sparc
  55. #include <alloca.h>
  56. #else
  57. #ifdef MSDOS
  58. #include <malloc.h>
  59. #else
  60. char *alloca ();
  61. #endif
  62. #endif
  63. #endif /* not __GNUC__ */
  64.  
  65. #if defined(STDC_HEADERS) || defined(__GNU_LIBRARY__)
  66. #  include <stdlib.h>
  67. #  include <string.h>
  68. #  define bcopy(s, d, n) memcpy ((d), (s), (n))
  69. #  define index strchr
  70. #else
  71.  
  72. #  ifdef USG
  73. #    include <string.h>
  74. #    define bcopy(s, d, n) memcpy ((d), (s), (n))
  75. #    define index strchr
  76. #  else
  77. #  include <strings.h>
  78. void bcopy ();
  79. #  endif
  80.  
  81. char *getenv ();
  82. char *malloc ();
  83. #endif
  84.  
  85. #ifdef MSDOS
  86. /* Include the <getopt.h> header file to insure consistency
  87.    of the prototypes.  */
  88. #include "getopt.h"
  89. static void exchange (char **argv);
  90. #endif /* MSDOS */
  91.  
  92. /* For communication from `getopt' to the caller.
  93.    When `getopt' finds an option that takes an argument,
  94.    the argument value is returned here.
  95.    Also, when `ordering' is RETURN_IN_ORDER,
  96.    each non-option ARGV-element is returned here.  */
  97.  
  98. char *optarg = 0;
  99.  
  100. /* Index in ARGV of the next element to be scanned.
  101.    This is used for communication to and from the caller
  102.    and for communication between successive calls to `getopt'.
  103.  
  104.    On entry to `getopt', zero means this is the first call; initialize.
  105.  
  106.    When `getopt' returns EOF, this is the index of the first of the
  107.    non-option elements that the caller should itself scan.
  108.  
  109.    Otherwise, `optind' communicates from one call to the next
  110.    how much of ARGV has been scanned so far.  */
  111.  
  112. int optind = 0;
  113.  
  114. /* The next char to be scanned in the option-element
  115.    in which the last option character we returned was found.
  116.    This allows us to pick up the scan where we left off.
  117.  
  118.    If this is zero, or a null string, it means resume the scan
  119.    by advancing to the next ARGV-element.  */
  120.  
  121. static char *nextchar;
  122.  
  123. /* Callers store zero here to inhibit the error message
  124.    for unrecognized options.  */
  125.  
  126. int opterr = 1;
  127.  
  128. /* Describe how to deal with options that follow non-option ARGV-elements.
  129.  
  130.    If the caller did not specify anything,
  131.    the default is REQUIRE_ORDER if the environment variable
  132.    _POSIX_OPTION_ORDER is defined, PERMUTE otherwise.
  133.  
  134.    REQUIRE_ORDER means don't recognize them as options;
  135.    stop option processing when the first non-option is seen.
  136.    This is what Unix does.
  137.    This mode of operation is selected by either setting the environment
  138.    variable _POSIX_OPTION_ORDER, or using `+' as the first character
  139.    of the list of option characters.
  140.  
  141.    PERMUTE is the default.  We permute the contents of ARGV as we scan,
  142.    so that eventually all the non-options are at the end.  This allows options
  143.    to be given in any order, even with programs that were not written to
  144.    expect this.
  145.  
  146.    RETURN_IN_ORDER is an option available to programs that were written
  147.    to expect options and other ARGV-elements in any order and that care about
  148.    the ordering of the two.  We describe each non-option ARGV-element
  149.    as if it were the argument of an option with character code 1.
  150.    Using `-' as the first character of the list of option characters
  151.    selects this mode of operation.
  152.  
  153.    The special argument `--' forces an end of option-scanning regardless
  154.    of the value of `ordering'.  In the case of RETURN_IN_ORDER, only
  155.    `--' can cause `getopt' to return EOF with `optind' != ARGC.  */
  156.  
  157. static enum
  158. {
  159.   REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
  160. } ordering;
  161.  
  162.  
  163. /* We have included <getopt.h>, so we'd better not redefine
  164.    struct option.  */
  165. #ifndef MSDOS
  166.  
  167. /* Describe the long-named options requested by the application.
  168.    _GETOPT_LONG_OPTIONS is a vector of `struct option' terminated by an
  169.    element containing a name which is zero.
  170.    The field `has_arg' is 1 if the option takes an argument,
  171.    2 if it takes an optional argument.  */
  172.  
  173. struct option
  174. {
  175.   char *name;
  176.   int has_arg;
  177.   int *flag;
  178.   int val;
  179. };
  180. #endif /* not MSDOS */
  181.  
  182. CONST struct option *_getopt_long_options;
  183.  
  184. int _getopt_long_only = 0;
  185.  
  186. /* Index in _GETOPT_LONG_OPTIONS of the long-named option actually found.
  187.    Only valid when a long-named option was found. */
  188.  
  189. int option_index;
  190.  
  191. /* Handle permutation of arguments.  */
  192.  
  193. /* Describe the part of ARGV that contains non-options that have
  194.    been skipped.  `first_nonopt' is the index in ARGV of the first of them;
  195.    `last_nonopt' is the index after the last of them.  */
  196.  
  197. static int first_nonopt;
  198. static int last_nonopt;
  199.  
  200. /* Exchange two adjacent subsequences of ARGV.
  201.    One subsequence is elements [first_nonopt,last_nonopt)
  202.     which contains all the non-options that have been skipped so far.
  203.    The other is elements [last_nonopt,optind), which contains all
  204.     the options processed since those non-options were skipped.
  205.  
  206.    `first_nonopt' and `last_nonopt' are relocated so that they describe
  207.     the new indices of the non-options in ARGV after they are moved.  */
  208.  
  209. static void
  210. exchange (argv)
  211.      char **argv;
  212. {
  213.   int nonopts_size = (last_nonopt - first_nonopt) * sizeof (char *);
  214.   char **temp = (char **) alloca (nonopts_size);
  215.  
  216.   /* Interchange the two blocks of data in ARGV.  */
  217.  
  218.   bcopy (&argv[first_nonopt], temp, nonopts_size);
  219.   bcopy (&argv[last_nonopt], &argv[first_nonopt],
  220.          (optind - last_nonopt) * sizeof (char *));
  221.   bcopy (temp, &argv[first_nonopt + optind - last_nonopt], nonopts_size);
  222.  
  223.   /* Update records for the slots the non-options now occupy.  */
  224.  
  225.   first_nonopt += (optind - last_nonopt);
  226.   last_nonopt = optind;
  227. }
  228.  
  229. /* Scan elements of ARGV (whose length is ARGC) for option characters
  230.    given in OPTSTRING.
  231.  
  232.    If an element of ARGV starts with '-', and is not exactly "-" or "--",
  233.    then it is an option element.  The characters of this element
  234.    (aside from the initial '-') are option characters.  If `getopt'
  235.    is called repeatedly, it returns successively each of the option characters
  236.    from each of the option elements.
  237.  
  238.    If `getopt' finds another option character, it returns that character,
  239.    updating `optind' and `nextchar' so that the next call to `getopt' can
  240.    resume the scan with the following option character or ARGV-element.
  241.  
  242.    If there are no more option characters, `getopt' returns `EOF'.
  243.    Then `optind' is the index in ARGV of the first ARGV-element
  244.    that is not an option.  (The ARGV-elements have been permuted
  245.    so that those that are not options now come last.)
  246.  
  247.    OPTSTRING is a string containing the legitimate option characters.
  248.    If an option character is seen that is not listed in OPTSTRING,
  249.    return '?' after printing an error message.  If you set `opterr' to
  250.    zero, the error message is suppressed but we still return '?'.
  251.  
  252.    If a char in OPTSTRING is followed by a colon, that means it wants an arg,
  253.    so the following text in the same ARGV-element, or the text of the following
  254.    ARGV-element, is returned in `optarg'.  Two colons mean an option that
  255.    wants an optional arg; if there is text in the current ARGV-element,
  256.    it is returned in `optarg', otherwise `optarg' is set to zero.
  257.  
  258.    If OPTSTRING starts with `-' or `+', it requests different methods of
  259.    handling the non-option ARGV-elements.
  260.    See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
  261.  
  262.    Long-named options begin with `+' instead of `-'.
  263.    Their names may be abbreviated as long as the abbreviation is unique
  264.    or is an exact match for some defined option.  If they have an
  265.    argument, it follows the option name in the same ARGV-element, separated
  266.    from the option name by a `=', or else the in next ARGV-element.
  267.    When `getopt' finds a long-named option, it returns 0 if that option's
  268.    `flag' field is nonzero, the value of the option's `val' field
  269.    otherwise.  */
  270.  
  271. int
  272. getopt (argc, argv, optstring)
  273.      int argc;
  274.      char **argv;
  275.      CONST char *optstring;
  276. {
  277.   optarg = 0;
  278.  
  279.   /* Initialize the internal data when the first call is made.
  280.      Start processing options with ARGV-element 1 (since ARGV-element 0
  281.      is the program name); the sequence of previously skipped
  282.      non-option ARGV-elements is empty.  */
  283.  
  284.   if (optind == 0)
  285.     {
  286.       first_nonopt = last_nonopt = optind = 1;
  287.  
  288.       nextchar = 0;
  289.  
  290.       /* Determine how to handle the ordering of options and nonoptions.  */
  291.  
  292.       if (optstring[0] == '-')
  293.         {
  294.           ordering = RETURN_IN_ORDER;
  295.           ++optstring;
  296.         }
  297.       else if (optstring[0] == '+')
  298.         {
  299.           ordering = REQUIRE_ORDER;
  300.           ++optstring;
  301.         }
  302.       else if (getenv ("_POSIX_OPTION_ORDER") != 0)
  303.         ordering = REQUIRE_ORDER;
  304.       else
  305.         ordering = PERMUTE;
  306.     }
  307.  
  308.   if (nextchar == 0 || *nextchar == 0)
  309.     {
  310.       if (ordering == PERMUTE)
  311.         {
  312.           /* If we have just processed some options following some non-options,
  313.              exchange them so that the options come first.  */
  314.  
  315.           if (first_nonopt != last_nonopt && last_nonopt != optind)
  316.             exchange (argv);
  317.           else if (last_nonopt != optind)
  318.             first_nonopt = optind;
  319.  
  320.           /* Now skip any additional non-options
  321.              and extend the range of non-options previously skipped.  */
  322.  
  323.           while (optind < argc
  324.                  && (argv[optind][0] != '-'
  325.                      || argv[optind][1] == 0)
  326.                  && (_getopt_long_options == 0
  327.                      || argv[optind][0] != '+'
  328.                      || argv[optind][1] == 0))
  329.             optind++;
  330.           last_nonopt = optind;
  331.         }
  332.  
  333.       /* Special ARGV-element `--' means premature end of options.
  334.          Skip it like a null option,
  335.          then exchange with previous non-options as if it were an option,
  336.          then skip everything else like a non-option.  */
  337.  
  338.       if (optind != argc && !strcmp (argv[optind], "--"))
  339.         {
  340.           optind++;
  341.  
  342.           if (first_nonopt != last_nonopt && last_nonopt != optind)
  343.             exchange (argv);
  344.           else if (first_nonopt == last_nonopt)
  345.             first_nonopt = optind;
  346.           last_nonopt = argc;
  347.  
  348.           optind = argc;
  349.         }
  350.  
  351.       /* If we have done all the ARGV-elements, stop the scan
  352.          and back over any non-options that we skipped and permuted.  */
  353.  
  354.       if (optind == argc)
  355.         {
  356.           /* Set the next-arg-index to point at the non-options
  357.              that we previously skipped, so the caller will digest them.  */
  358.           if (first_nonopt != last_nonopt)
  359.             optind = first_nonopt;
  360.           return EOF;
  361.         }
  362.  
  363.       /* If we have come to a non-option and did not permute it,
  364.          either stop the scan or describe it to the caller and pass it by.  */
  365.  
  366.       if ((argv[optind][0] != '-' || argv[optind][1] == 0)
  367.           && (_getopt_long_options == 0
  368.               || argv[optind][0] != '+' || argv[optind][1] == 0))
  369.         {
  370.           if (ordering == REQUIRE_ORDER)
  371.             return EOF;
  372.           optarg = argv[optind++];
  373.           return 1;
  374.         }
  375.  
  376.       /* We have found another option-ARGV-element.
  377.          Start decoding its characters.  */
  378.  
  379.       nextchar = argv[optind] + 1;
  380.     }
  381.  
  382.   if (_getopt_long_options != 0
  383.       && (argv[optind][0] == '+'
  384.           || (_getopt_long_only && argv[optind][0] == '-'))
  385.     )
  386.     {
  387.       CONST struct option *p;
  388.       char *s = nextchar;
  389.       int exact = 0;
  390.       int ambig = 0;
  391.       CONST struct option *pfound = 0;
  392.       int indfound;
  393.  
  394.       while (*s && *s != '=')
  395.         s++;
  396.  
  397.       /* Test all options for either exact match or abbreviated matches.  */
  398.       for (p = _getopt_long_options, option_index = 0; p->name;
  399.            p++, option_index++)
  400.         if (!strncmp (p->name, nextchar, s - nextchar))
  401.           {
  402.             if (s - nextchar == strlen (p->name))
  403.               {
  404.                 /* Exact match found.  */
  405.                 pfound = p;
  406.                 indfound = option_index;
  407.                 exact = 1;
  408.                 break;
  409.               }
  410.             else if (pfound == 0)
  411.               {
  412.                 /* First nonexact match found.  */
  413.                 pfound = p;
  414.                 indfound = option_index;
  415.               }
  416.             else
  417.               /* Second nonexact match found.  */
  418.               ambig = 1;
  419.           }
  420.  
  421.       if (ambig && !exact)
  422.         {
  423.           fprintf (stderr, "%s: option `%s' is ambiguous\n",
  424.                    argv[0], argv[optind]);
  425.           nextchar += strlen (nextchar);
  426.           optind++;
  427.           return '?';
  428.         }
  429.  
  430.       if (pfound != 0)
  431.         {
  432.           option_index = indfound;
  433.           optind++;
  434.           if (*s)
  435.             {
  436.               if (pfound->has_arg > 0)
  437.                 optarg = s + 1;
  438.               else
  439.                 {
  440.                   fprintf (stderr,
  441.                            "%s: option `%c%s' doesn't allow an argument\n",
  442.                            argv[0], argv[optind - 1][0], pfound->name);
  443.                   nextchar += strlen (nextchar);
  444.                   return '?';
  445.                 }
  446.             }
  447.           else if (pfound->has_arg == 1)
  448.             {
  449.               if (optind < argc)
  450.                 optarg = argv[optind++];
  451.               else
  452.                 {
  453.                   fprintf (stderr, "%s: option `%s' requires an argument\n",
  454.                            argv[0], argv[optind - 1]);
  455.                   nextchar += strlen (nextchar);
  456.                   return '?';
  457.                 }
  458.             }
  459.           nextchar += strlen (nextchar);
  460.           if (pfound->flag)
  461.             {
  462.               *(pfound->flag) = pfound->val;
  463.               return 0;
  464.             }
  465.           return pfound->val;
  466.         }
  467.       /* Can't find it as a long option.  If this is getopt_long_only,
  468.          and the option starts with '-' and is a valid short
  469.          option, then interpret it as a short option.  Otherwise it's
  470.          an error.  */
  471.       if (_getopt_long_only == 0 || argv[optind][0] == '+' ||
  472.           index (optstring, *nextchar) == 0)
  473.         {
  474.           if (opterr != 0)
  475.             fprintf (stderr, "%s: unrecognized option `%c%s'\n",
  476.                      argv[0], argv[optind][0], nextchar);
  477.           nextchar += strlen (nextchar);
  478.           optind++;
  479.           return '?';
  480.         }
  481.     }
  482.  
  483.   /* Look at and handle the next option-character.  */
  484.  
  485.   {
  486.     char c = *nextchar++;
  487.     char *temp = index (optstring, c);
  488.  
  489.     /* Increment `optind' when we start to process its last character.  */
  490.     if (*nextchar == 0)
  491.       optind++;
  492.  
  493.     if (temp == 0 || c == ':')
  494.       {
  495.         if (opterr != 0)
  496.           {
  497.             if (c < 040 || c >= 0177)
  498.               fprintf (stderr, "%s: unrecognized option, character code 0%o\n",
  499.                        argv[0], c);
  500.             else
  501.               fprintf (stderr, "%s: unrecognized option `-%c'\n",
  502.                        argv[0], c);
  503.           }
  504.         return '?';
  505.       }
  506.     if (temp[1] == ':')
  507.       {
  508.         if (temp[2] == ':')
  509.           {
  510.             /* This is an option that accepts an argument optionally.  */
  511.             if (*nextchar != 0)
  512.               {
  513.                 optarg = nextchar;
  514.                 optind++;
  515.               }
  516.             else
  517.               optarg = 0;
  518.             nextchar = 0;
  519.           }
  520.         else
  521.           {
  522.             /* This is an option that requires an argument.  */
  523.             if (*nextchar != 0)
  524.               {
  525.                 optarg = nextchar;
  526.                 /* If we end this ARGV-element by taking the rest as an arg,
  527.                    we must advance to the next element now.  */
  528.                 optind++;
  529.               }
  530.             else if (optind == argc)
  531.               {
  532.                 if (opterr != 0)
  533.                   fprintf (stderr, "%s: option `-%c' requires an argument\n",
  534.                            argv[0], c);
  535.                 c = '?';
  536.               }
  537.             else
  538.               /* We already incremented `optind' once;
  539.                  increment it again when taking next ARGV-elt as argument.  */
  540.               optarg = argv[optind++];
  541.             nextchar = 0;
  542.           }
  543.       }
  544.     return c;
  545.   }
  546. }
  547.  
  548. #ifdef TEST
  549.  
  550. /* Compile with -DTEST to make an executable for use in testing
  551.    the above definition of `getopt'.  */
  552.  
  553. int
  554. main (argc, argv)
  555.      int argc;
  556.      char **argv;
  557. {
  558.   int c;
  559.   int digit_optind = 0;
  560.  
  561.   while (1)
  562.     {
  563.       int this_option_optind = optind ? optind : 1;
  564.  
  565.       c = getopt (argc, argv, "abc:d:0123456789");
  566.       if (c == EOF)
  567.         break;
  568.  
  569.       switch (c)
  570.         {
  571.         case '0':
  572.         case '1':
  573.         case '2':
  574.         case '3':
  575.         case '4':
  576.         case '5':
  577.         case '6':
  578.         case '7':
  579.         case '8':
  580.         case '9':
  581.           if (digit_optind != 0 && digit_optind != this_option_optind)
  582.             printf ("digits occur in two different argv-elements.\n");
  583.           digit_optind = this_option_optind;
  584.           printf ("option %c\n", c);
  585.           break;
  586.  
  587.         case 'a':
  588.           printf ("option a\n");
  589.           break;
  590.  
  591.         case 'b':
  592.           printf ("option b\n");
  593.           break;
  594.  
  595.         case 'c':
  596.           printf ("option c with value `%s'\n", optarg);
  597.           break;
  598.  
  599.         case '?':
  600.           break;
  601.  
  602.         default:
  603.           printf ("?? getopt returned character code 0%o ??\n", c);
  604.         }
  605.     }
  606.  
  607.   if (optind < argc)
  608.     {
  609.       printf ("non-option ARGV-elements: ");
  610.       while (optind < argc)
  611.         printf ("%s ", argv[optind++]);
  612.       printf ("\n");
  613.     }
  614.  
  615.   exit (0);
  616. }
  617.  
  618. #endif /* TEST */
  619.